//#define __FORCE_TRACE__
//#define __FORCE_DEBUG__
//#define __FORCE_INFO__
#define THIS_FILE "client\fn_clientExecuteReleaseAI.sqf"
#include <tmf_constants.h>
#include <tmf_macros.h>

TRACE_1("Start",_this);
TMFPROFILERSTART;

private ["_caller","_target","_group","_object","_player","_actions","_released","_groups","_grp_ai","_action_id","_i"];
DEFAULT_PARAM(_target,0,east);
DEFAULT_PARAM(_caller,0,east);

_group = group _target;
_released = [];
_groups = (call CFUNC(hashEmpty));
{
	if (!isplayer _x) then {
		_object = _x;
		_actions = [_object,"LEAD"] call FFUNC(getActions);
		if (count _actions > 0) then {
			_action_id = [(_actions select 0)] call FFUNC(actionGetID);
			_grp_ai = [_groups, _action_id,grpNull] call CFUNC(hashGet);
			if (isNull _grp_ai) then {
				_grp_ai = [GVAR(own_side)] call CFUNC(createGroup);
				_groups = [_groups, _action_id,_grp_ai] call CFUNC(hashSet);
				[_grp_ai] call CFUNC(deleteWaypoints);
				_grp_ai addWaypoint [getPos _object, 20];
				_grp_ai addWaypoint [getPos _object, 50];
				_grp_ai setCurrentWaypoint [_grp_ai, 1];
				[_grp_ai, 1] setWaypointType "CYCLE";
				_grp_ai allowFleeing 0;
			};
			[_object] joinSilent _grp_ai;
			TRACE_2("Joined AI to Group",_object,_grp_ai);
			_released set[count _released, _object];
			(leader _grp_ai) doMove (waypointPosition [_grp_ai,(currentWaypoint _grp_ai)]);
		};
	}
} foreach units _group;

[_groups] spawn {
	private ["_groups","_i","_leader","_grp"];
	while {(count _groups > 0)} do {
		sleep 20.345678;
		for [{_i = 0},{_i < (count _groups)},{_i = _i + 1}] do {
			_grp = (_groups select _i);
			_leader = leader _grp;
			if (alive _leader) then {
				_leader doMove (waypointPosition [_grp,1]);
			} else {
				{	deletevehicle _x;
				} foreach units _grp;
				deletegroup _grp;
				_groups set [_i, "XxDeLxX"];
			};
		};
		_groups = _groups - ["XxDeLxX"];
	};
};
TRACE("End");
TMFPROFILERSTOP;